#include "comm.hpp"
#include <iostream>
int main()
{
  // 生成公共的key值
  key_t k = ftok(PATH_NAME, PROJ_ID);
  if (k < 0)
  {
    perror("ftok");
    exit(1);
  }
  Log("create key success ", Debug) << "client key:" << k << endl;

  // 获得共享内存
  int shmid = shmget(k, SHM_SIZE, 0);
  if (shmid == -1)
  {
    perror("shmid");
    exit(2);
  }
  Log("get shm success ", Debug) << "shmid:" << shmid << endl;

  // 将共享内存挂接到地址空间上
  char *shmaddr = (char *)shmat(shmid, nullptr, 0);
  Log("attach shm success ", Debug) << "shmid:" << shmid << endl;

  // 通信过程1
  /* char ch = 'a';
  for (ch = 'a'; ch <= 'd'; ch++) // 向共享内存中写入数据
  {
    snprintf(shmaddr, SIZE_MAX, "[%d] hello server I am Client :%c\n", getpid(), ch);
    sleep(3);
  }
  snprintf(shmaddr, sizeof(shmaddr), "quit");
 */
  // 通信过程2
  int fd = OPEN_FIFO(FIFE_NAME, WRITE);
  cout << "client fd:" << fd << endl;
  while (true)
  {
    ssize_t s = read(0, shmaddr, SHM_SIZE); // 0号文件描述符代表的是标准输入，即将数据直接从标准输入读进共享内存中，实现写数据操作
    if (s > 0)
    {
      shmaddr[s - 1] = 0;
      signal(fd);
      if (strcmp(shmaddr, "quit") == 0)
      {
        break;
      }
    }
  }
  CLOSE_FIFO(fd);

  // 将指定的共享内存，从自己的地址空间去关联

  shmdt(shmaddr);
  Log("detach shm success ", Debug) << "shmid:" << shmid << endl;

  return 0;
}